package com.ruoyi.web.controller.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Warning;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SmsTemplateCode;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SmsUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.WarningService;
import com.ruoyi.system.service.resp.EnergyRecordAreaResp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: ruohao
 * @Date: 2023/9/14
 **/
@RestController
@RequestMapping("/device/warning")
public class WarningController extends BaseController {
    @Resource
    private WarningService warningService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @PostMapping("/testMess")
    public AjaxResult testMess(Warning warning) {
        warningService.autoWarning();
        return AjaxResult.success();
    }

    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(Warning warning) {
        startPage();
        List<Warning> list = warningService.selectList(warning);
        return getDataTable(list);
    }

    @Log(title = "查询最近的10条预警信息", businessType = BusinessType.OTHER)
    @GetMapping("/tenList")
    public AjaxResult tenList(Warning warning) {
        List<Warning> list = warningService.selectTenList(warning);
        return AjaxResult.success(list);
    }


    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @GetMapping("/countList")
    public AjaxResult countList(Warning warning) {
        List<String> name = Arrays.asList("水温仪表", "水压仪表", "智能路灯");
        List<String> type = Arrays.asList("水温监测设备", "水压监测设备", "智能照明设备");

        List<Warning> list = new ArrayList<>();
        for (int i = 0; i < type.size(); i++) {
            Warning query = new Warning();
            query.setType(type.get(i));
            query.setName(name.get(i));
            query.setSearchTime(warning.getSearchTime());
            List<Warning> querys = warningService.selectList(query);

            if (!CollectionUtils.isEmpty(querys)) {
                query.setCount(querys.size());
            } else {
                query.setCount(0);
            }
            list.add(query);
        }
        return AjaxResult.success(list);
    }

    @Log(title = "设备列表导出", businessType = BusinessType.EXPORT)
    //("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Warning warning) {
        List<Warning> list = warningService.selectList(warning);
        ExcelUtil<Warning> util = new ExcelUtil<Warning>(Warning.class);
        util.exportExcel(response, list, "预警记录");
    }

    @Log(title = "查询人员管理All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(Warning warning) {
        List<Warning> list = warningService.selectList(warning);
        return getDataTable(list);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(warningService.selectById(id));
    }

    @Log(title = "新增人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Warning warning) {
        warning.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());


//            List<String> phones = sysUserMapper.getSmsPhonesWarning();
//            for (String phone : phones) {
//                Warning param = new Warning();
//                param.setDeviceId(warning.getDeviceId());
//                param.setDeviceType(warning.getType());
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                param.setTime(sdf.format(new Date()));
//                param.setContent(warning.getContent());
//                param.setAddress(warning.getLocation());
//                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(param));
//                SmsUtils.sendSms(SmsTemplateCode.WARNING.getCode(), phone, jsonObject);
//            }
//
//            warning.setRelease("1");

    Boolean result = warningService.create(warning);

        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "修改人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Warning warning) {
        warning.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = warningService.update(warning);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "删除人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(warningService.deleteById(id));
    }

    @Log(title = "首页预警记录", businessType = BusinessType.OTHER)
    @GetMapping("/fiveList")
    public AjaxResult list() {
        List<Warning> list = warningService.selectFiveList();
        return AjaxResult.success(list);
    }

    @GetMapping("/waterTemperatureData")//水温
    public AjaxResult waterTemperatureData(EnergyRecordAreaResp resp) {
        resp.setType("水温监测设备");
        resp.setTimeSeries(getZHTimeSeries());
        resp.setDataReport(getOneData(getZHTimeSeries(), "一区", resp));
        return success(resp);
    }

    @GetMapping("/waterPressureData")//水压
    public AjaxResult waterPressureData(EnergyRecordAreaResp resp) {
        resp.setType("水压监测设备");
        resp.setTimeSeries(getZHTimeSeries());
        resp.setDataReport(getOneData(getZHTimeSeries(), "二区", resp));
        return success(resp);
    }

    private List<Integer> getOneData(List<String> timeSeries, String location, EnergyRecordAreaResp resp) {
        List<Integer> one = new ArrayList<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String year = "";
        if (resp != null && StringUtils.isNotBlank(resp.getSearchDate())) {
            year = resp.getSearchDate();
        }

        for (String timeSery : timeSeries) {
            timeSery = timeSery.replace("月", "");
            Calendar calendar = Calendar.getInstance();
            if (StringUtils.isBlank(year)) {
                int i = calendar.get(Calendar.YEAR);
                year = i + "";
            }
            calendar.set(Integer.parseInt(year), Integer.parseInt(timeSery) - 1, 1); // 设置年份和月份
            int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 获取该月的最大天数
            String startTime = year + "-" + timeSery + "-01 00:00:00";
            String endTime = year + "-" + timeSery + "-" + lastDay + " 23:59:59";
            Integer amountByArea = warningService.selectListCount(startTime, endTime, resp.getType());
            one.add(amountByArea == null ? 0 : amountByArea);
        }
        return one;
    }

    private List<String> getZHTimeSeries() {
        List<String> result = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            result.add(i + "月");
        }
        return result;
    }

}
